﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Threading;
using Lon.IO.Ports;
using System.IO;
using System.Diagnostics;
using Lon.Data;


namespace Lon.UI
{
    public partial class FormRawData : DockContent
    {

        Dictionary<String, IRawDataProviders> moduleDict = new Dictionary<string, IRawDataProviders>();
        IRawDataProviders providers = null;
        IRawDataProvider DataProvider = null;
        bool dataUpdated = false;
        List<IRawDataRec> queueList = new List<IRawDataRec>(2000);
        private DevAge.ComponentModel.BoundList<IRawDataRec> mBoundList;
        public FormRawData(IRawDataProviders providers)
        {
            InitializeComponent();
            InitDataGrid();
            for (int i = 0; i < this.filterTypeList.Length; i++)
            {
                this.filterTypeList[i] = true;
            }
                this.providers = providers;
            
            for(int i=0;i<this.providers.RawDataProviders.Count;i++)
            {
            this.cmbProviderList.Items.Add(this.providers.RawDataProviders[i]);
          
            }
     
            updateHandle = new EventHandler<RawDataUpdateEventArgs>(DataProvider_DataUpdateHandler);
          
            cmbDir.SelectedIndex = 2;
            if (cmbProviderList.Items.Count > 0)
            {
                this.cmbProviderList.SelectedIndex = 0;
                this.DataProvider = (IRawDataProvider)cmbProviderList.Items[0];
                DataProvider.DataUpdateHandler += updateHandle;
            }

            this.cmbProviderList.SelectedIndexChanged += new EventHandler(cmbProviderList_SelectedIndexChanged);
         

        }

        void cmbProviderList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DataProvider.DataUpdateHandler -= updateHandle;
            }
            catch
            { 
            }

            queueList.Clear();

            this.DataProvider = (IRawDataProvider)this.cmbProviderList.SelectedItem;
            lock (DataProvider.RawDataRecs)
            {
                queueList.AddRange(DataProvider.RawDataRecs);
            }
            DataProvider.DataUpdateHandler += updateHandle;
        }

        private void InitDataGrid()
        {
            SourceGrid.DataGridColumn column;
            column = dataGrid.Columns.Add("Time", "时间", new TimeEditor());
            column.AutoSizeMode = SourceGrid.AutoSizeMode.None;
            column.Width = 100;
            column = dataGrid.Columns.Add("DataDir", "方向", new DirEditor());
            column.Width =100;
            column.AutoSizeMode= SourceGrid.AutoSizeMode.None;
            column=dataGrid.Columns.Add("Desp", "描述", typeof(String));
            column.Width = 200;
            column.AutoSizeMode = SourceGrid.AutoSizeMode.None;

            dataGrid.Columns.Add("DataStr", "数据", typeof(String)).AutoSizeMode =  SourceGrid.AutoSizeMode.EnableStretch;
            dataGrid.AutoStretchColumnsToFitWidth = true;
            dataGrid.SelectionMode = SourceGrid.GridSelectionMode.Row;
            dataGrid.Columns.StretchToFit();

            mBoundList = new DevAge.ComponentModel.BoundList<IRawDataRec>(queueList);
            dataGrid.DataSource = mBoundList;


        }
        EventHandler<RawDataUpdateEventArgs> updateHandle;
        void cmbDataProvider_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DataProvider.DataUpdateHandler -= updateHandle;
            }
            catch
            {
            }
            this.DataProvider = (IRawDataProvider)this.cmbProviderList.SelectedItem;
            queueList.Clear();
            lock (DataProvider.RawDataRecs)
            {
                queueList.AddRange(DataProvider.RawDataRecs);
            }
            DataProvider.DataUpdateHandler += updateHandle;
        }

        void DataProvider_DataUpdateHandler(object sender, RawDataUpdateEventArgs e)
        {
            if (RunStart == false) return;
            IRawDataRec rec = e.Rec;
            if (rec.Data[4] == 0x0f) return;
            if (this.filterTypeList[rec.Data[14]] == false) return;
            lock (queueList)
            {
                if (queueList.Count > 1998)
                {
                    queueList.RemoveAt(0);
                }
                queueList.Add(rec);
            }
            dataUpdated = true;

        }

    
        bool RunStart = false;
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (RunStart == false)
            {
                this.RunStart = true;
                toolStripButton1.Image = global::Lon.UI.Station.Properties.Resources.Stop;

            }
            else
            {
                this.RunStart = false;
                toolStripButton1.Image = global::Lon.UI.Station.Properties.Resources.start;

            }
        }



        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            if (sfd.ShowDialog() != DialogResult.OK) return;
            using (StreamWriter sw = new StreamWriter(sfd.FileName))
            {
                lock (queueList)
                {
                    for (int i = 0; i < queueList.Count; i++)
                    {
                        sw.WriteLine("[{0:F}][方向{1}]:{2}",
                            new object[] { queueList[i].Time, queueList[i].DataDir, queueList[i].Desp });
                        sw.WriteLine(queueList[i].DataStr);
                    }
                }
            }

        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            lock (queueList)
            {
                queueList.Clear();
            }
            this.dataGrid.Invalidate();


        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (dataUpdated == false) return;
            dataUpdated = false;
            this.dataGrid.Invalidate();
            this.dataGrid.RecalcCustomScrollBars();
            //dataGrid.Selection.ResetSelection(false);
            //dataGrid.Selection.SelectRow(queueList.Count, true);
            if (gotoLastRow)
                dataGrid.Selection.Focus(new SourceGrid.Position(queueList.Count, 0), true);
        }
        bool gotoLastRow = true;


        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (gotoLastRow == false)
            {
                gotoLastRow = true;
                toolStripButton4.BackColor = Color.LimeGreen;

            }
            else
            {
                gotoLastRow = false;
                toolStripButton4.BackColor = Color.Red;

            }
        }
        private bool[] filterTypeList = new bool[256];
        private FormFilter formFilter;
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (formFilter == null || formFilter.IsDisposed)
            {
                formFilter = new FormFilter(filterTypeList);
            }
            formFilter.ShowDialog();

        }


    }

    public class DirEditor : SourceGrid.Cells.Editors.TextBox
    {
        public DirEditor()
            : base(typeof(DataDir))
        {
        }
        public override string ValueToDisplayString(object p_Value)
        {
            try
            {
                if (p_Value == null) return "";
                DataDir dir = (DataDir)p_Value;
                if (dir == DataDir.Recive)
                {
                    return "接收";
                }
                else if (dir == DataDir.Transmit)
                {
                    return "发送";
                }
                else
                {
                    return "未知";
                }
            }
            catch
            {
                return "";
            }

        }
    }
    /// <summary>
    /// 定义设备属性的输出字符串
    /// </summary>
    class TimeEditor : SourceGrid.Cells.Editors.EditorBase
    {
        public TimeEditor()
            : base(null)
        {
        }
        public override string ValueToDisplayString(object p_Value)
        {
            if (p_Value == null) return "";
            DateTime time = (DateTime)p_Value;


            return time.ToString("HH:mm:ss.fff");

        }


    }

}
